package com.dg.gaming.client;
/*
 * DG (DG Gaming Engine) - API
 * Copyright (C) 2004  Bob Marks (marksie531@yahoo.com)
 * http://code.google.com/p/dng-gaming
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
import nanoxml.XMLElement;
import com.dg.gaming.api.common.*;
import com.dg.gaming.api.common.msg.*;
import com.dg.gaming.api.common.playerstate.*;



public class ClientCommDataReceiver {
    private Game game = null; // Game object.

    /**
     * Constructor which takes a game object.
     *
     * @param game      Game object.
     * @param username  Client username.
     */
    public ClientCommDataReceiver(Game game) {
        this.game = game;
    }

    /**
     * Receive game message.
     *
     * @param message    Message.
     * @param gameID     Game ID .
     * @param username   Username of user.
     */
    public void receiveGameMessage(XMLElement message, long username) {

        try {
            String messageType = message.getName();

            // 1) Implementation of Comm commands
            if (messageType.equals(Msg.TABLE)) {
                Table table = new Table(message);
                table.getPlayerList().updateUsers(game.getUserList());
                game.getTableList().updateTable(table.getTableNum(), table);
            } else if (messageType.equals(Msg.USER)) {
                User user = new User(message);
                game.getUserList().addUser(user);
            } else if (messageType.equals(Msg.DISCONNECT)) {
                MsgDisconnect commDisconnect = new MsgDisconnect(message);
                long user = commDisconnect.getUserid();
                game.getUserList().removeUser(user);
                game.getTableList().removeUserFromTables(user);
            }
        } catch (TransmissionException transEx) {
            transEx.printStackTrace();
        }
    }

    /**
     * Receive table message which will update the data.
     *
     * @see com.dg.gaming.client.gui.ITable#receiveTableMessage(nanoxml.XMLElement, int)
     */
    public void receiveTableMessage(XMLElement message, long userid,
                                    String tableNum) {

        String messageType = message.getName();
        Table table = game.getTableList().getTable(tableNum);

        if (messageType.equals(Msg.JOIN_TABLE)) {
            receiveJoinTable(new MsgJoinTable(message), userid, table);
        } else if (messageType.equals(Msg.EXIT_TABLE)) {
            MsgExitTable commExitTable = new MsgExitTable(message);
            game.getTableList().removePlayer(commExitTable.getTableNum(),
                                             commExitTable.getUserid());
        } else if (messageType.equals(Msg.GAME_OVER)) {
            gameOver(new MsgGameOver(message), userid, table);
        } else if (messageType.equals(Msg.PLAYER_STATE)) {
            playerStateUpdate(new MsgPlayerState(message), table);
        } else if (messageType.equals(Msg.START_GAME)) {
            MsgStartGame commStartGame = new MsgStartGame(message);
            table.getPlayerList().setCurrentPlayer(commStartGame.
                    getCurrentPlayer());
        } else if (messageType.equals(Msg.NEXT_PLAYER)) {
            MsgNextPlayer commNextPlayer = new MsgNextPlayer(message);
            table.getPlayerList().setCurrentPlayer(commNextPlayer.getUserid());
        } else if (messageType.equals(Msg.TABLE_PROPERTY)) {
            MsgTableProperty commTableProperty = new MsgTableProperty(message);
            table.addProperty(commTableProperty.getKey(),
                              commTableProperty.getValue());
        }

    }

    /**
     * Receive a join table message.
     *
     * @param commJoinTable  Join table object.
     * @param username       Username.
     * @param table          Table object.
     */
    private void receiveJoinTable(MsgJoinTable commJoinTable, long userid,
                                  Table table) {

        PlayerList playerList = commJoinTable.getPlayerList();

        if (playerList == null) {
            // No player list, so just add the single player to the table.
            long joiningPlayerId = commJoinTable.getUserid();
            User joiningUser = game.getUserList().getUser(joiningPlayerId);
            table.addPlayer(joiningUser);
        } else {
            // This message has a player list, so use that to set the playerlist
            // at the table.

            // First, Augment the player objects in the playerList with their users.
            playerList.updateUsers(game.getUserList());

            // Now, set the playerlist at the table
            table.setPlayerList(playerList);
        }

        // Update anything depending on tablelist
        game.getTableList().refreshObservers();
    }

    /**
     * Recieve a game over message and update the user objects.
     *
     * @param commGameOver  CommGameOver object.
     * @param username      Username object.
     * @param table         Table number.
     */
    private void gameOver(MsgGameOver commGameOver, long username,
                          Table table) {
        // Depending on the status create the game over message
        GameOver gameOver = commGameOver.getGameOver();
        long[] players = gameOver.getPlayers();
        int[] results = gameOver.getResults();
        int[] newRatings = gameOver.getNewRatings();

        // Update ratings of each player
        for (int i = 0; i < players.length; i++) {
            User user = game.getUserList().getUser(players[i]);
            user.update(results[i], newRatings[i]);
        }
        // Up$date table object.
        table.gameOver();

        game.getUserList().refreshObservers();
    }

    /**
     * Player state change i.e. a player is standing up / sitting down etc.
     *
     * @param commPlayerState
     */
    private void playerStateUpdate(MsgPlayerState commPlayerState, Table table) {
        // Retreive state change
        PlayerState commState = commPlayerState.getState();

        // Retreive player
        PlayerList commPlayers = table.getPlayerList();
        Player commPlayer = commPlayers.getPlayer(commPlayerState.getUserid());

        // update state on client player
        if (commState == null || commPlayer == null) {
            System.out.println();
        }
        commPlayer.setState(commState);

        // Check to see if the seat number needs updated.
        if (commState instanceof PlayerStateSeated) {
            commPlayer.setSeatNum(commPlayerState.getSeatNum());
        } else if (commState instanceof PlayerStateViewing) {
            commPlayer.setSeatNum(Player.NOT_SEATED);
        }

        commPlayers.refreshObservers();
    }

}
